<?php
/**
 * @author GhostWei
 * @date Aug 6, 2012
 */
class controller_admin_system_setting extends system_user_controller_panel {
	
	private $concept = null;
	public function init() {
		if(!parent::init()) {
			return ;
		}
		$this->concept = new system_setting_concept($this->user->getLang());
		$this->_crumbs()->addPage(system_nav_page::create($this->language('System'))->setRoute('system/index'));
		$this->_crumbs()->addPage(system_nav_page::create($this->language('Setting'))->setRoute('system/setting/index'));
	}
	
	public function action_addnew() {
		$row = $this->concept->create();
		$this->view->row = $row;
		$row = $this->_saveRow($row, true);
		$this->view->referer = $this->referer;
		$this->_crumbs()->addPage(system_nav_page::create($this->language('New Setting'))->setRoute('system/setting/addnew'));
		$this->render('system/setting/row.phtml');
	}
	
	public function action_edit() {
		$name = trim($this->_param('name'));
		if(!($row = $this->concept->fetch(array('name = ?' => $name)))) {
			throw new collection_exception("The Setting is not Existing.");
		}
		$row = $this->_saveRow($row, false);
		$this->view->row = $row;
		$this->view->referer = $this->referer;
		$this->_crumbs()->addPage(system_nav_page::create($row->getName())->setRoute('system/setting/edit')->setParams(array('name' => $row->getName())));
		$this->render('system/setting/row.phtml');
	}
	
	private function _saveRow($row, $isNew) {
		if(!$this->getRequest()->isPost()) {
			return $row;
		}
		$this->referer = $this->_post('referer');
		$row->setName(trim($this->_post('name')));
		$row->setValue($this->_post('value'));	
		$row->setIsSystem(intval($this->_post('is_system')) ? 1 : 0);	
		$row->setDescription($this->_post('description'));		
		$this->_saveToDatabase($row, 'file', 'image', true, $isNew);	
		if(!$this->view->throwException) {
			$this->view->setting()->remove();
		}	
		return $row;
	}
		
	public function action_index() {
		$this->render();
	}
		
	public function action_image() {
		$this->render();
	}
	
	public function action_variate() {
		$this->_batchDelete($this->concept, 'name', 'name');
		$adapter = new system_paginator_adapter_concept($this->concept);
		$adapter->setCurrentPageNumber(intval($this->_param('page', 1)));
		$adapter->setLimit(30);
		$this->view->list = new system_paginator($adapter);
		$this->_crumbs()->addPage(system_nav_page::create($this->language('System Variate'))->setRoute('system/setting/variate'));
		$this->render();
	}
	
}
